package com.poten.service;


import com.poten.mapper.OrderMapper;
import com.poten.mapper.PayMapper;
import com.poten.pojo.Order;
import com.poten.pojo.TbPayLog;
import com.poten.utils.WechatPayUtils;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class PayService {
    @Resource
    PayMapper payMapper;
    @Resource
    OrderMapper orderMapper;


    public Map<String, Object> pay(String userId,String[] orderIdList) {
        Map<String, Object> map = new HashMap<String,Object>();
        StringBuffer stringBuffer = new StringBuffer();
        StringBuffer stringBuffer2 = new StringBuffer();
        boolean flag=false;
        for (int i = 0; i < orderIdList.length; i++) {
            String orderIdStr = orderIdList[i];
            // 根据订单id查询出详细订单数据
            Order order =orderMapper.getById(orderIdStr);
            if(order==null){
                flag = true;
            }
            //名称拼接
            stringBuffer.append(order.getName()+",");
            stringBuffer2.append(order.getOid()+",");
        }
        if(flag){
            map.put("msg","订单不存在");
            map.put("code","5000");
            return map;
        }

        // 支付日志表插入一条数据
        String pid = UUID.randomUUID().toString().replace("-","");
        // 支付日志表插入一条数据
        TbPayLog payLog = new TbPayLog();
        payLog.setPid(pid);
        payLog.setCreTime(LocalDateTime.now().toString());
        payLog.setPname(stringBuffer.toString());
        payLog.setPrice(130.0);
        payLog.setOidList(stringBuffer2.toString());
        payLog.setStates(0);

        payMapper.insert(payLog);
        // 发起支付，调用微信支付
        Map<String, String> stringStringMap = WechatPayUtils.callWechatPay(payLog);
        map.putAll(stringStringMap);
        map.put("pid",pid);
        // 返回一个map给前台，前台根据返回数据生成二维码
        return map;
    }


    public boolean checkOderPay(Map<String, String> map) {
        String total_fee = map.get("total_fee");
        String pid = map.get("out_trade_no");

        TbPayLog payLog = payMapper.selectById(pid);
        if(payLog==null){ // 看下支付日志表是否有数据
            return false;
        }

        // 更新支付日志表数据状态
        TbPayLog tbPayLog = new TbPayLog();
        tbPayLog.setPid(pid);
        tbPayLog.setStates(1);
        payMapper.updateById(tbPayLog);

        //更改所有订单状态
        String orderList = payLog.getOidList();
            Order order = new Order();
            order.setOid(orderList);
            order.setStates(1);
            orderMapper.updateByOId(order);

        return true;
    }

    public TbPayLog getById(String payLogId) {
        return  payMapper.getById(payLogId);
    }
}
